package com.example.studydemo.hmosnote.slice;

import com.example.studydemo.hmosnote.*;
import com.google.gson.Gson;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataUriUtils;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.agp.utils.TextAlignment;
import ohos.agp.window.dialog.ListDialog;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_CONTENT;
import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_PARENT;

public class MainAbilitySlice extends AbilitySlice {
    private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD000F00, "MainAbilitySlice");
    private List<NoteBean> list = new ArrayList<>();
    private NoteProvider noteProvider;
    private NoteGridProvider noteGridProvider;
    private Text tvCount, tvOrderType;
    private TextField tfSearch;
    private String mKeyWord = "";
    private int mOrderType = 1;
    private boolean isListView = true;
    private ListContainer listContainer;
    private Image ivMenu;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        Image ivWriteNote = (Image) findComponentById(ResourceTable.Id_iv_write_note);
        tvCount = (Text) findComponentById(ResourceTable.Id_tv_count);
        tvOrderType = (Text) findComponentById(ResourceTable.Id_tv_order_type);
        tfSearch = (TextField) findComponentById(ResourceTable.Id_tf_search);
        ivMenu = (Image) findComponentById(ResourceTable.Id_iv_menu);
        listContainer = (ListContainer) findComponentById(ResourceTable.Id_list);

        ivMenu.setClickedListener(component -> {
            isListView = !isListView;
            loadData();
        });
        tfSearch.addTextObserver((s, i, i1, i2) -> {
            mKeyWord = s;
            loadData();
        });
        tvOrderType.setClickedListener(component -> {
            String[] items = new String[]{"按创建时间排序", "按编辑时间排序", "按标题排序"};
            ListDialog listDialog = new ListDialog(getContext());
            listDialog.setAlignment(TextAlignment.BOTTOM);
            listDialog.setSize(MATCH_PARENT, MATCH_CONTENT);
            listDialog.setProvider(new PickerItemProvider(Arrays.asList(items), MainAbilitySlice.this));
            listDialog.setAutoClosable(true);
            listDialog.setItems(items);
            DirectionalLayout directionalLayout = new DirectionalLayout(MainAbilitySlice.this);
            //自定义标题
            listDialog.setTitleCustomComponent(directionalLayout);
            listDialog.setListener(new ListContainer.ItemClickedListener() {
                @Override
                public void onItemClicked(ListContainer listContainer, Component component, int i, long l) {
                    mOrderType = i + 1;
                    tvOrderType.setText(items[i]);
                    initData();
                    listDialog.hide();
                }
            }, null, null);

            listDialog.show();
        });

        loadData();
        ivWriteNote.setClickedListener(component -> {
            //Intent 对象之间传递信息的载体
            Intent i = new Intent();
            //不需要传参的时候使用OperationBuilder，自定义传参使用Parameters
            Operation operationBuilder = new Intent.OperationBuilder()
                    .withDeviceId("")//跳转哪个设备,空代表当前设备
                    .withBundleName("com.example.studydemo.hmosnote")//跳转哪个应用
                    .withAbilityName("com.example.studydemo.hmosnote.WriteNoteAbility")//跳转哪个页面
                    .build();
            // 把operation设置到intent中
            i.setOperation(operationBuilder);
            //
            startAbility(i);
        });

    }

    private void loadData() {
        if (isListView) {
            listContainer.setLayoutManager(new DirectionalLayoutManager());
            noteProvider = new NoteProvider(initData(), this);
            listContainer.setItemProvider(noteProvider);
            listContainer.setReboundEffect(true);
        } else {
            TableLayoutManager manager = new TableLayoutManager();
            manager.setColumnCount(3);
            listContainer.setLayoutManager(manager);
            noteGridProvider = new NoteGridProvider(initData(), this);
            listContainer.setItemProvider(noteGridProvider);
            listContainer.setReboundEffect(true);
        }


        listContainer.setItemClickedListener(new ListContainer.ItemClickedListener() {
            @Override
            public void onItemClicked(ListContainer listContainer, Component component, int position, long l) {
                String[] items = new String[]{"编辑", "删除"};
                ListDialog listDialog = new ListDialog(getContext());
                listDialog.setAlignment(TextAlignment.BOTTOM);
                listDialog.setSize(MATCH_PARENT, MATCH_CONTENT);
                listDialog.setTitleText("请选择操作");
                listDialog.setProvider(new PickerItemProvider(Arrays.asList(items), MainAbilitySlice.this));
                listDialog.setAutoClosable(true);
                listDialog.setItems(items);
                DirectionalLayout directionalLayout = new DirectionalLayout(MainAbilitySlice.this);
                //自定义标题
                listDialog.setTitleCustomComponent(directionalLayout);
                listDialog.setListener(new ListContainer.ItemClickedListener() {
                    @Override
                    public void onItemClicked(ListContainer listContainer, Component component, int i, long l) {
                        NoteBean noteBean = list.get(position);
                        switch (i) {
                            case 0:
                                //Intent 对象之间传递信息的载体
                                Intent intent1 = new Intent();
                                //不需要传参的时候使用OperationBuilder，自定义传参使用Parameters
                                Operation operationBuilder = new Intent.OperationBuilder()
                                        .withDeviceId("")//跳转哪个设备,空代表当前设备
                                        .withBundleName("com.example.studydemo.hmosnote")//跳转哪个应用
                                        .withAbilityName("com.example.studydemo.hmosnote.WriteNoteAbility")//跳转哪个页面
                                        .build();
                                // 把operation设置到intent中
                                intent1.setOperation(operationBuilder);
                                //参数
                                intent1.setParam("note", new Gson().toJson(noteBean));
                                startAbility(intent1);
                                break;
                            case 1:
                                DBUtils.getInstance(getContext()).deleteNote(noteBean);
                                initData();
                                break;
                        }
                        listDialog.hide();
                    }
                }, null, null);

                listDialog.show();
            }
        });
    }

    @Override
    public void onActive() {
        super.onActive();
        loadData();

    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    private List<NoteBean> initData() {
        List<NoteBean> query = DBUtils.getInstance(this).query(mKeyWord, mOrderType);
        list.clear();
        if (query.size() > 0) {
            HiLog.info(LABEL_LOG, query.size() + "");
            list.addAll(query);
        }
        if (noteProvider != null) {
            noteProvider.update(list);
        }
        tvCount.setText(query.size() + "篇备忘录");
        return query;
    }
}
